package com.yaozheng.vocationaltraining.activity;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.TextViewCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.adapter.HundredQuestionsEncyclopediaAdapter;
import com.yaozheng.vocationaltraining.adapter.PoWoDictionaryAdapter;
import com.yaozheng.vocationaltraining.adapter.PoWoDictionaryItemAdapter;
import com.yaozheng.vocationaltraining.bean.CategoriesBean;
import com.yaozheng.vocationaltraining.bean.CategoryItemBean;
import com.yaozheng.vocationaltraining.http.HttpCallback;
import com.yaozheng.vocationaltraining.http.HttpClient;
import com.yaozheng.vocationaltraining.http.HttpResult;
import com.yaozheng.vocationaltraining.iview.ILoadMoreView;
import com.yaozheng.vocationaltraining.iview.IPoWoDictionaryView;
import com.yaozheng.vocationaltraining.iview.ITokenBaseView;
import com.yaozheng.vocationaltraining.manage.ListViewLoadMoreManage;
import com.yaozheng.vocationaltraining.service.PoWoDictionaryService;
import com.yaozheng.vocationaltraining.service.impl.PoWoDictionaryServiceImpl;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.LogUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 宝沃词典
 *
 * @author Administrator
 */
@EActivity(R.layout.activity_po_wo_dictionary)
public class PoWoDictionaryActivity extends BaseActivity implements
        SwipeRefreshLayout.OnRefreshListener, ILoadMoreView, IPoWoDictionaryView {
    @ViewById
    ListView listView;
    @ViewById
    LinearLayout type_contain_layout;
    @ViewById
    CheckBox click_checkbox;
    @ViewById
    CheckBox lastest_checkbox;
    @ViewById
    EditText key_edittext;
    @ViewById
    ImageView search_imageview;

    /**
     * 下拉刷新
     */
    @ViewById
    SwipeRefreshLayout swipeRefreshLayout;

    ListViewLoadMoreManage listViewLoadMoreManage;

    @Bean(PoWoDictionaryServiceImpl.class)
    PoWoDictionaryService poWoDictionaryService;

    PoWoDictionaryItemAdapter poWoDictionaryAdapter;
    ArrayList<CategoryItemBean> categoryItemData = new ArrayList<>();

    int categoriyId;

    int lastId;
    List<CategoriesBean> list;

    LayoutInflater inflater;

    String sortStr = "click";

    int openDetailPosition;

    @AfterViews
    public void initView() {
        setHeadTitle("宝沃词典");
        poWoDictionaryService.init(this);
        inflater = this.getLayoutInflater();
        listViewLoadMoreManage = new ListViewLoadMoreManage(this, this,
                listView);
        swipeRefreshLayout.setOnRefreshListener(this);

        loadCategoriesData();

        poWoDictionaryAdapter = new PoWoDictionaryItemAdapter(this,
                categoryItemData);
        listView.setAdapter(poWoDictionaryAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                openDetailPosition = position;
                if(!TextUtils.isEmpty(categoryItemData.get(position).getDetail())){
                    poWoDictionaryAdapter.setselectedPosition(openDetailPosition);
                }else{
                    poWoDictionaryService.detail(categoryItemData.get(position).getId());
                }


            }
        });

        refreshSortStatus();

        key_edittext
                .setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    public boolean onEditorAction(TextView v, int actionId,
                                                  KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_SEND
                            || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
//让mPasswordEdit获取输入焦点
                            if(!TextUtils.isEmpty(key_edittext.getEditableText().toString())){
                                onRefresh();
                            }
                        return true;
                    }
                        return false;
                    }
                });
        search_imageview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!TextUtils.isEmpty(key_edittext.getEditableText().toString())){
                    onRefresh();
                }
            }
        });

        click_checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sortStr = "click";

                if(lastest_checkbox.getCompoundDrawables()[2] != null){
                    lastest_checkbox.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
                }
                if(click_checkbox.getCompoundDrawables()[2] != null){
//                    lastest_checkbox.setCompoundDrawables(null,null,null,null);
                }else{
                    click_checkbox.setCompoundDrawablesWithIntrinsicBounds(null,null,
                        PoWoDictionaryActivity.this.getResources().
                                getDrawable(R.drawable.checkbox_sort_right_bg),null);
                }
//
                refreshSortStatus();
            }
        });
        lastest_checkbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sortStr = "id";
                if(click_checkbox.getCompoundDrawables()[2] != null){
//                    click_checkbox.setCompoundDrawablesRelative();
                    click_checkbox.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
                }
                if(lastest_checkbox.getCompoundDrawables()[2] != null){
//                    lastest_checkbox.setCompoundDrawables(null,null,null,null);
                }else{
                    lastest_checkbox.setCompoundDrawablesWithIntrinsicBounds(null,null,
                            PoWoDictionaryActivity.this.getResources().
                                    getDrawable(R.drawable.checkbox_sort_right_bg),null);
                }
                refreshSortStatus();

            }
        });

    }

    private void refreshSortStatus() {
        if("click".equals(sortStr)){//1表示按关注排序
            click_checkbox.setBackgroundColor(this.getResources().getColor(R.color.footer_bg_color));
            lastest_checkbox.setBackgroundColor(this.getResources().getColor(R.color.default_bg_color));
            click_checkbox.setTextColor(this.getResources().getColor(R.color.default_bg_color));
            lastest_checkbox.setTextColor(this.getResources().getColor(R.color.black));
        }else{
            lastest_checkbox.setBackgroundColor(this.getResources().getColor(R.color.footer_bg_color));
            click_checkbox.setBackgroundColor(this.getResources().getColor(R.color.default_bg_color));
            lastest_checkbox.setTextColor(this.getResources().getColor(R.color.default_bg_color));
            click_checkbox.setTextColor(this.getResources().getColor(R.color.black));
        }
        onRefresh();
    }

    private void loadCategoriesData() {
        poWoDictionaryService.loadCategories();
    }

    @Override
    public void onRefresh() {
        lastId = 0;
        loadData();

    }

    public void loadData() {

        String sort = "desc";
        if("click".equals(sortStr)){//表示按关注排序
            if(click_checkbox.isChecked()){
                sort = "desc";
            }else{
                sort = "asc";
            }
        }else{
            if(lastest_checkbox.isChecked()){
                sort = "desc";
            }else{
                sort = "asc";
            }
        }


        poWoDictionaryService.list(lastId,categoriyId,
                key_edittext.getEditableText().toString(),sortStr,sort);
    }

    @UiThread
    @Override
    public void responseSuccess(JSONObject jsonObject) {
        try {
            cancelLoadDataProgressDialog();
            JSONArray dataList = TypeUtils.getJsonArray(jsonObject, "data","items");
            if (dataList != null) {
                if (lastId == 0) {
                    categoryItemData.clear();
                }

                for (int i = 0; i < dataList.size(); i++) {
                    JSONObject jsonObject2 = dataList.getJSONObject(i);

                    CategoryItemBean bean = new CategoryItemBean();
                    bean.setId(jsonObject2.getInt("id"));
                    bean.setCateId(jsonObject2.getInt("cateId"));
                    bean.setCateName(jsonObject2.getString("cateName"));
                    bean.setClick(jsonObject2.getInt("click"));
                    bean.setTitle(jsonObject2.getString("title"));
                    bean.setCreatedTime(jsonObject2.getString("createdTime"));

                    categoryItemData.add(bean);
                }

                poWoDictionaryAdapter.setData(categoryItemData,categoriyId);
                poWoDictionaryAdapter.notifyDataSetChanged();

            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }
    }

    @UiThread
    @Override
    public void responseError(String error) {
        cancelLoadDataProgressDialog();
        alertMessage(error);
    }

    @Override
    public void loadMoreData() {
        if (poWoDictionaryAdapter != null) {
            if(list != null && list.size() > 0){
                int lastId = list.get(list.size() -1).getId();
                if (lastId > 0) {
                    this.lastId = lastId;
                    loadData();
                }
            }

        }
    }

    @Override
    public void cancelLoadDataProgressDialog() {
        swipeRefreshLayout.setRefreshing(false);
        listViewLoadMoreManage.loadMoreComplete();
    }

    @Override
    public void categoriesListSuccess(JSONObject jsonObject) {
        LogUtils.println(jsonObject.toString());

        JSONArray categoriesList = TypeUtils.getJsonArray(jsonObject,"data",
                "categories");

        list = new ArrayList<>();
        CategoriesBean allBean = new CategoriesBean();
        allBean.setId(0);
        allBean.setActiveIcon(null);
        allBean.setIcon(null);
        allBean.setName("全部辞典");
        list.add(allBean);

        for (int i = 0; i < categoriesList.size(); i++) {
            JSONObject jsonObject2 = categoriesList.getJSONObject(i);

            CategoriesBean bean = new CategoriesBean();
            bean.setId(jsonObject2.getInt("id"));
            bean.setActiveIcon(jsonObject2.getString("activeIcon"));
            bean.setIcon(jsonObject2.getString("icon"));
            bean.setName(jsonObject2.getString("name"));
            list.add(bean);
        }

        if(list != null && list.size() > 0){
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    for(int i= 0 ; i < list.size() ; i++){
                        CategoriesBean bean = list.get(i);
                        View dictionaryItemLayout = inflater.inflate(R.layout.dictionary_item
                                , null);
                        dictionaryItemLayout.setTag(bean.getId());
                        ImageView iconImageView = (ImageView) dictionaryItemLayout.findViewById(R.id.icon_imageview);
                        TextView nameTextView = (TextView) dictionaryItemLayout.findViewById(R.id.name_textview);

                        nameTextView.setText(bean.getName());


                        if(categoriyId == bean.getId()){
                            if(i == 0){
                                iconImageView.setImageResource(R.drawable.icon_study_class_all_now);
                            }else{
                                Glide.with(PoWoDictionaryActivity.this.getApplicationContext())
                                        .load(bean.getActiveIcon())
                                        .crossFade()
                                        .into(iconImageView);
                            }
                            nameTextView.setTextColor(PoWoDictionaryActivity.this.getResources().getColor(R.color.footer_bg_color));
                        }else{
                            if(i == 0){
                                iconImageView.setImageResource(R.drawable.icon_study_class_all);
                            }else{
                                Glide.with(PoWoDictionaryActivity.this.getApplicationContext())
                                        .load(bean.getIcon())
                                        .crossFade()
                                        .into(iconImageView);
                            }
                            nameTextView.setTextColor(Color.BLACK);
                        }

                        dictionaryItemLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                categoriyId = (int) view.getTag();

                                for(int i = 0 ; i < type_contain_layout.getChildCount() ; i++){
                                    View childView = type_contain_layout.getChildAt(i);
                                    if(childView.getTag().toString().equals(view.getTag().toString())){
                                        if(categoriyId == 0){
                                            ((ImageView) childView.findViewById(R.id.icon_imageview)).setImageResource(R.drawable.icon_study_class_all_now);
                                        }else{
                                            Glide.with(PoWoDictionaryActivity.this.getApplicationContext())
                                                    .load(list.get(i).getActiveIcon())
                                                    .crossFade()
                                                    .into((ImageView) childView.findViewById(R.id.icon_imageview));
                                        }
                                        ((TextView) childView.findViewById(R.id.name_textview)).setTextColor(PoWoDictionaryActivity.this.getResources().getColor(R.color.footer_bg_color));
                                    }else{
                                        if(i == 0){
                                            ((ImageView) childView.findViewById(R.id.icon_imageview)).setImageResource(R.drawable.icon_study_class_all);
                                        }else{
                                            Glide.with(PoWoDictionaryActivity.this.getApplicationContext())
                                                    .load(list.get(i).getIcon())
                                                    .crossFade()
                                                    .into((ImageView) childView.findViewById(R.id.icon_imageview));
                                        }
                                        ((TextView) childView.findViewById(R.id.name_textview)).setTextColor(Color.BLACK);
                                    }
                                }

                                onRefresh();
                            }
                        });
                        type_contain_layout.addView(dictionaryItemLayout);
                    }


                }
            });
        }


        onRefresh();

    }

    @Override
    public void categoriesListError(String error) {
        LogUtils.println(error);
    }

    @Override
    public void detailSuccess(JSONObject jsonObject) {
        JSONObject detailObject = TypeUtils.getJsonObject(jsonObject,"data",
                "item");
        categoryItemData.get(openDetailPosition).setDetail(detailObject.getString("body"));

        PoWoDictionaryActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                poWoDictionaryAdapter.setselectedPosition(openDetailPosition);
            }
        });
    }

    @Override
    public void detailError(String serverConnectionError) {

    }
}
